<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

use  App\Models\Phone;

use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;


class PhoneController extends Controller
{
    public function newPhone(Request $request)
    {
        // imei battery lat lng brand
        $input = Input::only('imei', 'battery','lat','lng','brand','wechat_uid','version');
  
        $validator = Validator::make($input, [        
            'imei'      => 'required',
            'battery'         => 'required',
            'lat'     =>  'required',
            'lng'     =>  'required',
            'brand'     =>  'required',
            'version'     =>  'required',
            'wechat_uid'     => 'nullable|string',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $data['imei'] = $input['imei'];
        $data['battery'] = $input['battery'];
        $data['lat'] = $input['lat'];
        $data['lng'] = $input['lng'];
        $data['brand'] = $input['brand'];
        $data['version'] = $input['version'];
        $data['wechat_uid'] = $input['wechat_uid']??'';
        $where['imei'] = $input['imei'];
        $exist = Phone::where($where)->first();
        if($data['wechat_uid']){
            $weixin_exist = Phone::where('wechat_uid',$input['wechat_uid'])->first();
            if($weixin_exist){
                $weixin_exist->wechat_uid = '';
                $weixin_exist->save();
            }
        }
        if($exist){
            $exist->battery = $input['battery'];
            $exist->lat = $input['lat'];
            $exist->lng = $input['lng'];
            $exist->version = $input['version'];
            $exist->wechat_uid = $input['wechat_uid']??'';
            $exist->save();
        }else{
            Phone::create($data);
        }
        return $this->returnOk();
    }

    
}